import sqlite3
import os

def get_lottery_draws():
    # 连接数据库
    conn = sqlite3.connect('lottery.db')
    cursor = conn.cursor()
    
    # 查询最新的1000条记录
    cursor.execute("""
        SELECT draw_num, draw_date, 
               red_ball_1, red_ball_2, red_ball_3, red_ball_4, red_ball_5, red_ball_6, 
               blue_ball
        FROM lottery_draws
        ORDER BY draw_num DESC
        LIMIT 1000
    """)
    
    records = cursor.fetchall()
    conn.close()
    return records

def format_record(record):
    # 格式化红球号码
    red_balls = ' '.join(str(num).zfill(2) for num in record[2:8])
    # 格式化蓝球号码
    blue_ball = str(record[8]).zfill(2)
    
    # 返回格式化的表格行
    return f"| {record[0]} | {record[1]} | {red_balls} | {blue_ball} |"

def update_ssq_md():
    # 读取开奖记录
    records = get_lottery_draws()
    
    # 读取现有的ssq.md文件内容
    with open('ssq.md', 'r', encoding='utf-8') as f:
        content = f.readlines()
    
    # 找到表格开始的位置
    table_start = -1
    for i, line in enumerate(content):
        if '| 期号 | 开奖日期 | 红球号码 | 蓝球号码 |' in line:
            table_start = i
            break
    
    if table_start == -1:
        print("Error: Could not find table header in ssq.md")
        return
    
    # 保留表头之前的内容
    new_content = content[:table_start + 2]
    
    # 添加新的记录
    for record in records:
        new_content.append(format_record(record) + '\n')
    
    # 写入文件
    with open('ssq.md', 'w', encoding='utf-8') as f:
        f.writelines(new_content)

if __name__ == '__main__':
    update_ssq_md()
    print("ssq.md has been updated successfully!")